package com.grom.constant;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

import com.grom.velocity.DaoCreator;
import com.grom.xml.XmlParser;

public abstract class VelocityUtil {

	public static void initVelocity() {
		File targetFolder = new File(FileUtil.getWorkSpaceLocation().getAbsolutePath() + "/tmp/");
		if (!targetFolder.exists()) {
			targetFolder.mkdirs();
		}
		Velocity.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, targetFolder.getAbsolutePath());
		Velocity.setProperty(Velocity.INPUT_ENCODING, "UTF-8");
	}

	public static VelocityContext buildVelocityContext(InputStream ins) {
		initVelocity();
		XmlParser parser = new XmlParser(ins);
		Properties properties = new Properties();
		Velocity.init(properties);
		VelocityContext context = new VelocityContext();
		context.put("list", parser.getAllProperties());
		context.put("nameList", parser.getAllPropertiesName());
		context.put("allName", parser.getAllPropertiesName());
		context.put("className", parser.getClassName());
		return context;
	}

	public static Template buildVelocityTemplate(String fileName) {
		try {
			BufferedInputStream bins = new BufferedInputStream(DaoCreator.class.getResource(fileName).openStream());
			File targetFolder = new File(FileUtil.getWorkSpaceLocation().getAbsolutePath() + "/tmp/");
			if (!targetFolder.exists()) {
				targetFolder.mkdirs();
			}
			BufferedOutputStream bous = new BufferedOutputStream(new FileOutputStream(targetFolder.getAbsolutePath()
					+ "/" + fileName));
			byte[] tmp = new byte[2048];
			int l;
			while ((l = bins.read(tmp)) > 0) {
				bous.write(tmp, 0, l);
			}
			bous.flush();
			bous.close();
			bins.close();
			System.out.println("register the FILE_RESOURCE_LOADER_PATH with [" + targetFolder.getAbsolutePath() + "]");
			Velocity.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, "c:\\");
			Velocity.setProperty(Velocity.INPUT_ENCODING, "UTF-8");
			return Velocity.getTemplate(fileName);
		} catch (IOException e) {
			System.out.println(e.getMessage() + " VelocityUtil.buildVelocityTemplate(" + fileName + ")");
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}
}
